'use client';

import React, { useState, useEffect } from 'react';

export default function EditorPage({ params }) {
  const projectId = params.id;
  const [content, setContent] = useState('在此处编辑项目内容...');
  const [lastSaved, setLastSaved] = useState(null);
  const [isSaving, setIsSaving] = useState(false);
  
  // 从本地存储加载内容
  useEffect(() => {
    try {
      const savedData = localStorage.getItem(`project-${projectId}`);
      if (savedData) {
        const parsed = JSON.parse(savedData);
        setContent(parsed.content || '');
        setLastSaved(parsed.lastSaved || null);
      }
    } catch (error) {
      console.error('加载内容失败', error);
    }
  }, [projectId]);
  
  // 保存内容到本地存储
  const handleSave = () => {
    setIsSaving(true);
    
    try {
      const saveTime = new Date().toISOString();
      localStorage.setItem(`project-${projectId}`, JSON.stringify({
        content,
        lastSaved: saveTime
      }));
      
      setLastSaved(saveTime);
      alert('保存成功！');
    } catch (error) {
      console.error('保存失败', error);
      alert('保存失败，请查看控制台');
    } finally {
      setIsSaving(false);
    }
  };
  
  return (
    <div className="p-4 max-w-4xl mx-auto">
      <div className="flex justify-between items-center mb-4">
        <div>
          <h1 className="text-2xl font-bold">项目编辑器</h1>
          <p className="text-sm text-gray-500">项目ID: {projectId}</p>
          {lastSaved && (
            <p className="text-xs text-gray-500">
              上次保存: {new Date(lastSaved).toLocaleString()}
            </p>
          )}
        </div>
        <button
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400"
          onClick={handleSave}
          disabled={isSaving}
        >
          {isSaving ? '保存中...' : '保存'}
        </button>
      </div>
      
      <div className="border rounded shadow-sm p-2">
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          className="w-full min-h-[400px] p-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
          placeholder="在此处编辑内容..."
        />
      </div>
      
      <div className="mt-4 text-sm text-gray-500">
        <p>提示: 内容将保存在浏览器的本地存储中。</p>
      </div>
    </div>
  );
}